# app/api/v1/family/family.py
from fastapi import APIRouter, Query, Path
from typing import Optional

from app.controllers.family.family_system import family_controller  # 假设你已经创建了家庭控制器
from app.schemas.family.family_system import FamilyCreate, FamilyUpdate
from app.utils.request import RequestHandler

from app.schemas.base.login import CredentialsSchema, JWTOut, JWTPayload
from app.core.auth import get_current_user_required,get_current_superuser
from fastapi import APIRouter, Depends, Query

router = APIRouter()

@router.get("/list", summary="获取家庭列表")
async def get_families(
    name: Optional[str] = Query(None, description="家庭名称"),
    current_user: JWTPayload = Depends(get_current_superuser)   ## 限制管理员使用
):
    """获取家庭树结构"""
    try:
        family_tree = await family_controller.get_family_tree(name)
        return RequestHandler.success(data=family_tree, message="获取家庭列表成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.get("/{family_id}", summary="获取家庭详情")
async def get_family(
    family_id: int = Path(..., description="家庭ID"),
):
    """获取家庭详情"""
    try:
        family_obj = await family_controller.get_family_info(family_id)
        data = await family_obj.to_dict() if hasattr(family_obj, 'to_dict') else family_obj
        return RequestHandler.success(data=data, message="获取家庭详情成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.post("/create", summary="创建家庭")
async def create_family(
    family_in: FamilyCreate,
    current_user: JWTPayload = Depends(get_current_user_required),
):
    """创建家庭"""
    try:
        # 假设需要传入创建者ID，这里可以从前端或认证信息获取
        # 这里简化处理，实际应该从依赖注入获取当前用户  已经修改
        family_obj = await family_controller.create_family(family_in,creator_id=None)
        data = await family_obj.to_dict() if hasattr(family_obj, 'to_dict') else family_obj
        return RequestHandler.created(data=data, message="家庭创建成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.put("/{family_id}", summary="更新家庭")
async def update_family(
    family_id: int = Path(..., description="家庭ID"),
    family_in: FamilyUpdate = None,
):
    """更新家庭"""
    try:
        if family_in:
            family_in.id = family_id
        family_obj = await family_controller.update_family(family_in)
        data = await family_obj.to_dict() if hasattr(family_obj, 'to_dict') else family_obj
        return RequestHandler.success(data=data, message="家庭更新成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.delete("/{family_id}", summary="删除家庭")
async def delete_family(
    family_id: int = Path(..., description="家庭ID"),
    current_user: JWTPayload = Depends(get_current_superuser)   ## 限制管理员使用
):
    """删除家庭"""
    try:
        result = await family_controller.delete_family(family_id)
        if result:
            return RequestHandler.success(message="家庭删除成功")
        else:
            return RequestHandler.error(message="家庭删除失败")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.get("/{family_id}/info", summary="获取家庭详细信息")
async def get_family_info(
    family_id: int = Path(..., description="家庭ID"),
):
    """获取家庭详细信息（包含成员）"""
    try:
        family_info = await family_controller.get_family_info(family_id)
        return RequestHandler.success(data=family_info, message="获取家庭信息成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.post("/{family_id}/members", summary="添加家庭成员")
async def add_family_member(
    family_id: int = Path(..., description="家庭ID"),
    user_id: int = Query(..., description="用户ID"),
    nickname: Optional[str] = Query(None, description="家庭昵称"),
    is_admin: bool = Query(False, description="是否为管理员"),
):
    """添加家庭成员"""
    try:
        member = await family_controller.add_family_member(
            family_id=family_id,
            user_id=user_id,
            nickname=nickname,
            is_admin=is_admin
        )
        data = await member.to_dict() if hasattr(member, 'to_dict') else member
        return RequestHandler.success(data=data, message="添加家庭成员成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.delete("/{family_id}/members/{user_id}", summary="移除家庭成员")
async def remove_family_member(
    family_id: int = Path(..., description="家庭ID"),
    user_id: int = Path(..., description="用户ID"),
):
    """移除家庭成员"""
    try:
        member = await family_controller.remove_family_member(family_id, user_id)
        data = await member.to_dict() if hasattr(member, 'to_dict') else member
        return RequestHandler.success(data=data, message="移除家庭成员成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))

@router.get("/user/{user_id}", summary="获取用户所属家庭")
async def get_user_families(
    user_id: int = Path(..., description="用户ID"),
):
    """获取用户所属的所有家庭"""
    try:
        families = await family_controller.get_user_families(user_id)
        families_data = []
        for family in families:
            if hasattr(family, 'to_dict'):
                families_data.append(await family.to_dict())
            else:
                families_data.append(family)
        return RequestHandler.success(data=families_data, message="获取用户家庭成功")
    except Exception as e:
        return RequestHandler.server_error(message=str(e))